package com.kexin.jbsg.feiliu;

import java.util.LinkedList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.android.feiliu.AlixId;
import com.alipay.android.feiliu.BaseHelper;
import com.alipay.android.feiliu.MobileSecurePayHelper;
import com.alipay.android.feiliu.MobileSecurePayer;
import com.alipay.android.feiliu.ResultChecker;
import com.kexin.jbsg.util.Util;

/**
 * @author oven:
 * @version 创建时间：2013-4-20 上午10:12:48
 * 
 */
public class PayActivityAlipay extends Activity{
	private Button paybtn;
	private ProgressDialog mProgress = null;
	
	public Spinner spinner_rechargeValue;
	public EditText inputValue;
	public Button btn_backGame;
	public TextView welCome;
	
	public CheckBox cb_type1;
	public CheckBox cb_type2;
	
	public String userId;
	public String userRoleId;
	public String serverId;
	public String roleName;
	public String channel;
	
	public static LinkedList<CardValueItem> selValues;
	public static final int[] chooseValue = {1,5,10,15,18,20,25,30,50,60,68,100,120,180,208,250,300,468,500};
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pay_activity_alipay);
		
		userId = PayActivity.userId;
		userRoleId = PayActivity.userRoleId;
		serverId = PayActivity.serverId;
		roleName = PayActivity.roleName;
		channel = PayActivity.channel;
		
		welCome = (TextView) findViewById(R.id.recharge_alipay_userRole);
		welCome.setText(welCome.getText()+roleName);
		
		//确定按钮
		paybtn = (Button) findViewById(R.id.recharge_alipay);
		paybtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				boolean checked =  true;
				int rechargeValue = 0;//充值金额
				//检查方式
				if(cb_type1.isChecked()){
					//选择方式
					rechargeValue = ((CardValueItem)spinner_rechargeValue.getSelectedItem()).getValue();
				}else{
					//自输入
					String sinp = inputValue.getText().toString().trim();
					if(sinp.equals("")){
						checked = false;
						inputValue.setError("选择方式2,输入金额不能为空!");
					}else{
						rechargeValue = Integer.parseInt(sinp);
						if(rechargeValue<1){
							checked = false;
							inputValue.setError("选择方式2,输入金额必须大于1元");
						}
					}
				}
				if(checked){
					// 检测安全支付服务是否被安装
					MobileSecurePayHelper mspHelper = new MobileSecurePayHelper(PayActivityAlipay.this);
					boolean isMobile_spExist = mspHelper.detectMobile_sp();
					if (!isMobile_spExist){
						return;
					}
					//生成订单,获取字符串
					int cardType = 116;//支付宝
					StringBuffer paramsb = new StringBuffer();
					//OrderType
					paramsb.append("OrderType="+cardType);
					//Denomination
					paramsb.append("&Denomination="+rechargeValue);
					//serverId
					paramsb.append("&serverId="+serverId);
					//userId
					paramsb.append("&userId="+userId);
					//userRoleId
					paramsb.append("&userRoleId="+userRoleId);
					//channel
					paramsb.append("&channel="+channel);
					
					String sign =PayActivityCard.getMD5Str(userId+","+userRoleId+","+serverId+","+PayActivity.key);
					paramsb.append("&sign="+sign);
					
					payAli(paramsb.toString());
					
					closeProgress();
					mProgress = BaseHelper.showProgress(PayActivityAlipay.this, null, "正在创建订单", false,true);
				}
			}
		});
		
		
		//下拉选框
		spinner_rechargeValue = (Spinner) findViewById(R.id.spinner_recharge_alipay);
		//自定义adapter
		ArrayAdapter<CardValueItem> adapter = new ArrayAdapter<CardValueItem>(this, android.R.layout.simple_spinner_item, getSelValues()) {
            @Override
            public View getDropDownView(int position, View convertView, ViewGroup parent) {
                View view = getLayoutInflater().inflate(R.layout.kom_spinner, parent, false);
                //文本
                TextView label = (TextView) view.findViewById(R.id.kom_spinner_label);
                label.setText(getItem(position).getValueString());
                //图标
                if (spinner_rechargeValue.getSelectedItemPosition() == position) {
                    //label.setTextColor(getResources().getColor(R.color.selected_fg));
                   // view.setBackgroundColor(color_white);
                    view.findViewById(R.id.kom_spinner_icon).setVisibility(View.VISIBLE);
                }
                return view;
            }
        };
        spinner_rechargeValue.setAdapter(adapter);
		
        
        //输入
        inputValue = (EditText) findViewById(R.id.recharge_alipay_money);
        
        //cb1
        cb_type1 = (CheckBox) findViewById(R.id.recharge_cb_sel);
        //cb2
        cb_type2 = (CheckBox) findViewById(R.id.recharge_cb_inp);
        cb_type1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					cb_type2.setChecked(false);
					spinner_rechargeValue.setEnabled(true);
					inputValue.setEnabled(false);
				}
			}
		});
        cb_type1.setChecked(true);
        
        cb_type2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					cb_type1.setChecked(false);
					spinner_rechargeValue.setEnabled(false);
					inputValue.setEnabled(true);
				}
			}
		});
        
        
        btn_backGame = (Button) findViewById(R.id.recharge_alipay_backGame);
	    btn_backGame.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				PayActivityAlipay.this.finish();
			}
		});
        
	}
	
	
	public void payAli(final String params){
		final Handler hd = new Handler(){
			@Override
			public void handleMessage(Message msg) {
				boolean result = msg.getData().getBoolean("result");
				if(result){
					Toast.makeText(PayActivityAlipay.this, "创建订单订单成功",Toast.LENGTH_SHORT).show();
					String rechargeInfo = msg.getData().getString("rechargeInfo");
					//打开支付宝进行支付
					MobileSecurePayer msp = new MobileSecurePayer();
					boolean rechargeResult = msp.pay(rechargeInfo, mHandler, AlixId.RQF_PAY, PayActivityAlipay.this);
					if (rechargeResult) {
						// 显示“正在支付”进度条
//						closeProgress();
//						mProgress = BaseHelper.showProgress(TabActivity2.this, null, "正在支付", false,true);
					} 
				}else{
					Toast.makeText(PayActivityAlipay.this, "创建订单失败",Toast.LENGTH_SHORT).show();
				}
			}
		};
		
		new Thread(){
			public void run() {
				String result  = null;
				Message msg = new Message();
				Bundle data = new Bundle();
				try {
					result = Util.getWebCon(PayActivity.createOrderUrl+params);	
					if(result.startsWith("success:")){
						data.putBoolean("result", true);
						data.putString("rechargeInfo", result.replace("success:",""));
						msg.setData(data);
						hd.sendMessage(msg);
					}else{
						data.putBoolean("result", false);
						hd.sendMessage(msg);
					}
				} catch (Exception e) {
					data.putBoolean("result", false);
					hd.sendMessage(msg);
				}
				closeProgress();
			};
		}.start();
	}
	
	// 这里接收支付结果，支付宝手机端同步通知
	private Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			try {
				String strRet = (String) msg.obj;

				switch (msg.what) {
				case AlixId.RQF_PAY: {
//					closeProgress();
					// 此处将提示给开发人员具体的交易状态码，
					// 由于安全支付服务付款成功以后会有提示展示给用户，所以建议在上线版本中不进行额外提示
					// 以免造成用户提示的混乱。
					// 从通知中获取参数
					try {
						// 获取交易状态，具体状态代码请参看文档
						String tradeStatus = "resultStatus=";
						int imemoStart = strRet.indexOf("resultStatus=");
						imemoStart += tradeStatus.length();
						int imemoEnd = strRet.indexOf(";memo=");
						tradeStatus = strRet.substring(imemoStart, imemoEnd);

						// 对通知进行验签
						ResultChecker resultChecker = new ResultChecker(strRet);

						int retVal = resultChecker.checkSign();
						// 返回验签结果以及交易状态
						// 验签失败
						if (retVal == ResultChecker.RESULT_CHECK_SIGN_FAILED) {
							BaseHelper.showDialog(
									PayActivityAlipay.this,
									"提示",
									"您的订单信息已被非法篡改。",
									android.R.drawable.ic_dialog_alert);
						} else {
//							BaseHelper.showDialog(TabActivity2.this, "提示", "状态码:"
//									+ tradeStatus, R.drawable.infoicon);
						}

					} catch (Exception e) {
						e.printStackTrace();

						BaseHelper.showDialog(PayActivityAlipay.this, "提示", strRet,
								R.drawable.infoicon);
					}
				}
					break;
				}

				super.handleMessage(msg);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	};
		
	// 关闭进度框
	void closeProgress() {
		try {
			if (mProgress != null) {
				mProgress.dismiss();
				mProgress = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static class AlixOnCancelListener implements
		DialogInterface.OnCancelListener {
		Activity mcontext;
		
		public AlixOnCancelListener(Activity context) {
			mcontext = context;
		}
		
		public void onCancel(DialogInterface dialog) {
			mcontext.onKeyDown(KeyEvent.KEYCODE_BACK, null);
		}
	}
	
	
	public static LinkedList<CardValueItem> getSelValues(){
		if(selValues==null){
			selValues = new LinkedList<CardValueItem>();
			for(int i=0;i<chooseValue.length;i++){
				CardValueItem item = new CardValueItem();
				item.setValue(chooseValue[i]);
				selValues.add(item);
			}
		}
		return selValues;
	}
	
	
	
}

